import urequests

from machine import Timer,Pin

# 参数设置
HOST = "https://gitee.com/gushihui/mpy/raw/master/"
switch = Pin(15,Pin.OUT,value=1)
timer = Timer(-1)               # 定时器 - 循环定时开关
timer_net = Timer(-2)           # 定时器 - 定时读取网络数据
time_wind = [1,2]             # [开,关]，LED相反[关,开]
time_net = 30*60*1000

def timer_init(pin,time_wind_new=None):
    print(time.localtime())
    global time_wind
    if time_wind_new and (time_wind != time_wind_new):
        pin_status = pin.value()
        time_wind_temp = time_wind_new[pin_status]*60*1000 - timer.value()
        if time_wind_temp>0:
            timer.deinit()
            time_wind = time_wind_new
            timer.init(period=time_wind_temp,mode=Timer.ONE_SHOT,callback=lambda t: timer_init(pin))
        else:
            timer.deinit()
            time_wind = time_wind_new
            timer.init(period=time_wind_new[not pin_status]*60*1000,mode=Timer.ONE_SHOT,callback=lambda t: timer_init(pin))
    else:
        pin.value(not pin.value())
        timer.init(period=time_wind[pin.value()]*60*1000,mode=Timer.ONE_SHOT,callback=lambda t:timer_init(pin))
    LED.value(not pin.value())
        
def get_net_setting():
    global HOST,switch,time_wind
    try:
        print("start get net data...")
        time_wind_new = urequests.get(HOST + "wind.json").json()["wind_set"]
        if time_wind_new and (time_wind != time_wind_new):
            print("reset wind setting")
            time_wind = time_wind_new
            timer_init(switch,time_wind)
    except:
        pass

if __name__ == "__main__":
    get_net_setting()
    timer_net.init(period=time_net,mode=Timer.PERIODIC,callback=lambda t:get_net_setting())
    timer_init(switch)